
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Tama_Chan.Entities_ns;
using Tama_Chan.FontParticleEngine_ns;
using Tama_Chan.ParticleEngine_ns;
using Tama_Chan.PhysicsEngine_ns;
using Tama_Chan.UI;


namespace Tama_Chan.GameEngine_ns
{
   public class GameEngine
   {
      public const float BackgroundDepth = 1.0f;
      public const float GatewayTeleporterDepth = 0.9f;
      public const float EnemyDepth = 0.8f;
      public const float PlayerDepth = 0.7f;
      public const float ParticleDepth = 0.6f;
      public const float FontParticleDepth = 0.5f;
      public const float GuiRootDepth = 0.1f;

      public const int MaxFood = 8;
      public const int TeleporterCount = 4;
      public const float PlayerSpeed = 30f;

      public PhysicsEngine PhysicsEngine { get; set; }
      public FontParticleEngine FontParticleEngine { get; set; }
      public ParticleEngine ParticleEngine { get; set; }

      public IList<GameEntity> GameEntityList { get; private set; }
      public IList<Food> FoodList { get; set; }
      public IList<Enemy> EnemyList { get; set; }
      public IList<Teleporter> TeleporterList { get; set; }

      public Texture2D BackgroundTexture { get; set; }
      public Texture2D SquareTexture { get; set; }
      public Texture2D Square60x60Texture { get; set; }
      public Texture2D CircleTexture { get; private set; }
      public Texture2D MysteryTexture { get; private set; }
      public Texture2D PowerPelletTexture { get; private set; }

      public SoundEffect BloopSoundEffect { get; set; }
      public SoundEffect PopSoundEffect { get; set; }
      public SoundEffect HitWallSoundEffect { get; private set; }
      public SoundEffect GulpSoundEffect { get; private set; }
      public SoundEffect OofSoundEffect { get; set; }
      public SoundEffect ZzoopSoundEffect { get; set; }
      public SoundEffect MysterySoundEffect { get; set; }
      public SoundEffect ChaseSoundEffect { get; set; }

      public Game1 Game1 { get; private set; }
      public SpriteFont ScoreFont { get; set; }
      public SpriteFont GameOverFont { get; set; }
      public Player Player { get; set; }
      public Mystery Mystery { get; set; }
      public PowerPellet PowerPellet { get; set; }
      public int HighScore { get; set; }
      public int Health { get; set; }
      public GameState GameState { get; set; }

		public int MaxEnemies = 1;
		private int score;
		public int Score
		{
   		get
   		{
				return score; 
   		}
			set
			{
				score = value;
				if(score > 16000)
				{
					MaxEnemies = 4;
				}
				else if(score > 8000)
				{
					MaxEnemies = 3;
				}
				else if(score > 4000)
				{
					MaxEnemies = 2;
				}
			}
		}

      // GUI Textures
      private Texture2D WhiteSquareTexture { get; set; }
      private Texture2D AppNameLabelTexture { get; set; }
      private Texture2D BackButtonTexture { get; set; }
      private Texture2D GameOverLabelTexture { get; set; }
      private Texture2D GuiBackgroundTexture { get; set; }
      private Texture2D HowToPlayTexture { get; set; }
      private Texture2D InfoButtonTexture { get; set; }
      private Texture2D InfoLabelTexture { get; set; }
      private Texture2D PausedLabelTexture { get; set; }
      private Texture2D PlayButtonTexture { get; set; }

      // GUI Widgets
      private Widget GuiContainer { get; set; }
      private Widget HomeContainer { get; set; }
      private Widget InfoContainer { get; set; }
      private Widget PausedContainer { get; set; }
      private Widget GameOverContainer { get; set; }
      private Widget AppNameLabel { get; set; }
      private Widget PlayButton { get; set; }
      private Widget InfoButton { get; set; }
      private Widget InfoLabel { get; set; }
      private Widget HowToPlayLabel { get; set; }
      private Widget InfoBackButton { get; set; }
      private Widget PausedLabel { get; set; }
      private Widget PausedBackButton { get; set; }
      private Widget GameOverLabel { get; set; }
      private Widget GameOverBackButton { get; set; }

      private bool TouchesHaveBeenProcessed { get; set; }

		private bool IsTrial { get; set; }


      public GameEngine(Game1 game1)
      {
         Game1 = game1;

//#if DEBUG
//         Guide.SimulateTrialMode = true;
//#endif
			IsTrial = Guide.IsTrialMode;

         // Build engines
         PhysicsEngine = new PhysicsEngine(this);
         FontParticleEngine = new FontParticleEngine(this);
         ParticleEngine = new ParticleEngine(this);
      }


      public void Initialize()
      {
         // Build sound effects
         BloopSoundEffect = Game1.Content.Load<SoundEffect>(@"Sounds\bloop");
         HitWallSoundEffect = Game1.Content.Load<SoundEffect>(@"Sounds\hitWall");
         PopSoundEffect = Game1.Content.Load<SoundEffect>(@"Sounds\pop");
         GulpSoundEffect = Game1.Content.Load<SoundEffect>(@"Sounds\gulp");
         OofSoundEffect = Game1.Content.Load<SoundEffect>(@"Sounds\oof");
         ZzoopSoundEffect = Game1.Content.Load<SoundEffect>(@"Sounds\zzoop");
         MysterySoundEffect = Game1.Content.Load<SoundEffect>(@"Sounds\mystery");
         ChaseSoundEffect = Game1.Content.Load<SoundEffect>(@"Sounds\chase");

         // Initialize engines
         FontParticleEngine.Initialize();
         ParticleEngine.Initialize();
      }


      public void LoadContent()
      {
         // Game Textures
         BackgroundTexture = Game1.Content.Load<Texture2D>(@"Images\background");
         SquareTexture = Game1.Content.Load<Texture2D>(@"Images\square");
         Square60x60Texture = Game1.Content.Load<Texture2D>(@"Images\square60x60");
         CircleTexture = Game1.Content.Load<Texture2D>(@"Images\circle");
         MysteryTexture = Game1.Content.Load<Texture2D>(@"Images\mystery");
         PowerPelletTexture = Game1.Content.Load<Texture2D>(@"Images\star");

         // GUI Textures
         WhiteSquareTexture = Game1.Content.Load<Texture2D>(@"Images\GUI\whiteSquare_10x10");
         AppNameLabelTexture = Game1.Content.Load<Texture2D>(@"Images\GUI\appNameLabel");
         BackButtonTexture = Game1.Content.Load<Texture2D>(@"Images\GUI\backButton");
         GameOverLabelTexture = Game1.Content.Load<Texture2D>(@"Images\GUI\gameOverLabel");
         GuiBackgroundTexture = Game1.Content.Load<Texture2D>(@"Images\GUI\guiBackground");
         HowToPlayTexture = Game1.Content.Load<Texture2D>(@"Images\GUI\howToPlay");
         InfoButtonTexture = Game1.Content.Load<Texture2D>(@"Images\GUI\infoButton");
         InfoLabelTexture = Game1.Content.Load<Texture2D>(@"Images\GUI\infoLabel");
         PausedLabelTexture = Game1.Content.Load<Texture2D>(@"Images\GUI\pausedLabel");
         PlayButtonTexture = Game1.Content.Load<Texture2D>(@"Images\GUI\playButton");

         // Fonts
         ScoreFont = Game1.Content.Load<SpriteFont>(@"Fonts\ScoreFont");
         GameOverFont = Game1.Content.Load<SpriteFont>(@"Fonts\GameOverFont");

         // Load engine contents
         FontParticleEngine.LoadContent();
         ParticleEngine.LoadContent();

         BuildGUIContainer();
         BuildHomeContainer();
      }


   	private void ResetGame()
      {
         // If the game is being re-started, clean up sounds and particles through entities and engines
         SetStateForAllSounds(SoundState.Stopped);

         // Get high score
         using(IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
         {
            if(file.FileExists("save"))
            {
               using(var reader = new BinaryReader(file.OpenFile("save", FileMode.Open)))
               {
                  try
                  {
                     HighScore = reader.ReadInt32();
                  }
                  catch
                  {
                     // do nothing
                  }
               }
            }
         }

         // Set general state
         Health = 100;
   		Score = 0;
   		MaxEnemies = 1;

         // Create all entity lists
         GameEntityList = new List<GameEntity>();
         FoodList = new List<Food>(MaxFood);
         EnemyList = new List<Enemy>(MaxEnemies);
         TeleporterList = new List<Teleporter>(TeleporterCount);

         // Helpers for placing entities
         int left = Game1.GameBounds.Left + 5;
         int gatewayRight = Game1.GameBounds.Right - SquareTexture.Width - 5;
         int teleporterRight = Game1.GameBounds.Right - Square60x60Texture.Width - 5;
         int top = Game1.GameBounds.Top + 5;
         int gatewayBottom = Game1.GameBounds.Bottom - SquareTexture.Height - 5;
         int teleporterBottom = Game1.GameBounds.Bottom - Square60x60Texture.Height - 5;
         int horizontalMiddle = (Game1.GameBounds.Width - Square60x60Texture.Width) / 2;
         int verticalMiddle = Game1.GameBounds.Top + ((Game1.GameBounds.Height - Square60x60Texture.Height) / 2);

         // Add Player
         Player = new Player(this, new Vector2(horizontalMiddle + (CircleTexture.Width / 2f), verticalMiddle + (CircleTexture.Height / 2f)));
         GameEntityList.Add(Player);

         // Add Gateways
         GameEntityList.Add(new Gateway(this, new Vector2(left, top)));
         GameEntityList.Add(new Gateway(this, new Vector2(gatewayRight, top)));
         GameEntityList.Add(new Gateway(this, new Vector2(left, gatewayBottom)));
         GameEntityList.Add(new Gateway(this, new Vector2(gatewayRight, gatewayBottom)));

         // Add Teleporters
         var northTeleporter = new Teleporter(this, new Vector2(horizontalMiddle, top));
         var southTeleporter = new Teleporter(this, new Vector2(horizontalMiddle, teleporterBottom));
         var eastTeleporter = new Teleporter(this, new Vector2(teleporterRight, verticalMiddle));
         var westTeleporter = new Teleporter(this, new Vector2(left, verticalMiddle));
         northTeleporter.TargetTeleporter = southTeleporter;
         southTeleporter.TargetTeleporter = northTeleporter;
         eastTeleporter.TargetTeleporter = westTeleporter;
         westTeleporter.TargetTeleporter = eastTeleporter;
         GameEntityList.Add(northTeleporter);
         TeleporterList.Add(northTeleporter);
         GameEntityList.Add(southTeleporter);
         TeleporterList.Add(southTeleporter);
         GameEntityList.Add(eastTeleporter);
         TeleporterList.Add(eastTeleporter);
         GameEntityList.Add(westTeleporter);
         TeleporterList.Add(westTeleporter);

         // Add Mystery
         Mystery = new Mystery(this);
         GameEntityList.Add(Mystery);

         // Add PowerPellet
         PowerPellet = new PowerPellet(this);
         GameEntityList.Add(PowerPellet);

         // Clear all particle effects and particles
         ParticleEngine.ParticleEffects.Clear();
         FontParticleEngine.FontParticles.Clear();
      }


   	private void SetStateForAllSounds(SoundState soundState)
      {
         if(GameEntityList == null)
         {
            return;
         }

         for(int i = 0; i < GameEntityList.Count; i++)
         {
            var gameEntity = GameEntityList[i];

            if(gameEntity.SoundOne != null)
            {
               var soundOne = gameEntity.SoundOne;

               switch(soundState)
               {
                  case SoundState.Playing:
                     if(gameEntity.SoundOne.State == SoundState.Paused)
                     {
                        soundOne.Resume();
                     }
                     break;
                  case SoundState.Paused:
                     if(soundOne.State == SoundState.Playing)
                     {
                        soundOne.Pause();
                     }
                     break;
                  case SoundState.Stopped:
                     if(soundOne.State == SoundState.Playing)
                     {
                        soundOne.Stop();
                     }
                     break;
               }
            }

            if(gameEntity.SoundTwo != null)
            {
               var soundTwo = gameEntity.SoundTwo;

               switch(soundState)
               {
                  case SoundState.Playing:
                     if(soundTwo.State == SoundState.Stopped)
                     {
                        soundTwo.Play();
                     }
                     else if(soundTwo.State == SoundState.Paused)
                     {
                        soundTwo.Resume();
                     }
                     break;
                  case SoundState.Paused:
                     if(soundTwo.State == SoundState.Playing)
                     {
                        soundTwo.Pause();
                     }
                     break;
                  case SoundState.Stopped:
                     if(soundTwo.State == SoundState.Playing)
                     {
                        soundTwo.Stop();
                     }
                     break;
               }
            }
         }
      }


      private void BuildGUIContainer()
      {
         GuiContainer = new Widget(Game1.SpriteBatch, GuiBackgroundTexture.Bounds, GuiBackgroundTexture)
         {
            Name = "GuiContainer",
            IsContainer = true,
            Depth = GuiRootDepth
         };
      }


      private void BuildHomeContainer()
      {
         // Sub-container. Needs a user-defined size instead of getting one from it's texture because the
         // texture is simply a stretched rectangle. Color is used to give this some solid color.
         HomeContainer = new Widget(Game1.SpriteBatch, new Rectangle(0, 0, 400, 400), WhiteSquareTexture)
         {
            Name = "HomeContainer",
            IsContainer = true,
            HorizontalAlignment = HorizontalAlignment.Center,
            CurrentColor = Color.Black,
            MarginTop = 20
         };
         GuiContainer.AddWidget(HomeContainer);

         // 'Tama-Chan' name label
         AppNameLabel = new Widget(Game1.SpriteBatch, AppNameLabelTexture.Bounds, AppNameLabelTexture)
         {
            Name = "AppNameLabel",
            HorizontalAlignment = HorizontalAlignment.Center,
            MarginTop = 10
         };
         HomeContainer.AddWidget(AppNameLabel);

         // Play Button
         PlayButton = new Widget(Game1.SpriteBatch, PlayButtonTexture.Bounds, PlayButtonTexture)
         {
            Name = "PlayButton",
            HorizontalAlignment = HorizontalAlignment.Center,
            MarginTop = 20
         };
         HomeContainer.AddWidget(PlayButton);

         // Info Button
         InfoButton = new Widget(Game1.SpriteBatch, InfoButtonTexture.Bounds, InfoButtonTexture)
         {
            Name = "InfoButton",
            HorizontalAlignment = HorizontalAlignment.Center,
            MarginTop = 20
         };
         HomeContainer.AddWidget(InfoButton);
      }


      private void BuildInfoContainer()
      {
         InfoContainer = new Widget(Game1.SpriteBatch, new Rectangle(0, 0, 400, 400), WhiteSquareTexture)
         {
            Name = "InfoContainer",
            IsContainer = true,
            HorizontalAlignment = HorizontalAlignment.Center,
            CurrentColor = Color.Black,
            MarginTop = 20
         };
         GuiContainer.AddWidget(InfoContainer);

         HowToPlayLabel = new Widget(Game1.SpriteBatch, HowToPlayTexture.Bounds, HowToPlayTexture)
         {
            Name = "HowToPlayLabel",
            HorizontalAlignment = HorizontalAlignment.Center
         };
         InfoContainer.AddWidget(HowToPlayLabel);

         InfoBackButton = new Widget(Game1.SpriteBatch, BackButtonTexture.Bounds, BackButtonTexture)
         {
            Name = "InfoBackButton",
            HorizontalAlignment = HorizontalAlignment.Center,
            MarginTop = 30
         };
         InfoContainer.AddWidget(InfoBackButton);
      }


      private void BuildPausedContainer()
      {
         PausedContainer = new Widget(Game1.SpriteBatch, new Rectangle(0, 0, 400, 400), WhiteSquareTexture)
         {
            Name = "PausedContainer",
            IsContainer = true,
            HorizontalAlignment = HorizontalAlignment.Center,
            CurrentColor = Color.Black,
            MarginTop = 20
         };
         GuiContainer.AddWidget(PausedContainer);

         PausedLabel = new Widget(Game1.SpriteBatch, PausedLabelTexture.Bounds, PausedLabelTexture)
         {
            Name = "PausedLabel",
            HorizontalAlignment = HorizontalAlignment.Center
         };
         PausedContainer.AddWidget(PausedLabel);

         PausedBackButton = new Widget(Game1.SpriteBatch, BackButtonTexture.Bounds, BackButtonTexture)
         {
            Name = "PausedBackButton",
            HorizontalAlignment = HorizontalAlignment.Center
         };
         PausedContainer.AddWidget(PausedBackButton);
      }


      private void BuildGameOverContainer()
      {
         GameOverContainer = new Widget(Game1.SpriteBatch, new Rectangle(0, 0, 400, 400), WhiteSquareTexture)
         {
            Name = "GameOverContainer",
            IsContainer = true,
            HorizontalAlignment = HorizontalAlignment.Center,
            CurrentColor = Color.Black,
            MarginTop = 20
         };
         GuiContainer.AddWidget(GameOverContainer);

         GameOverLabel = new Widget(Game1.SpriteBatch, GameOverLabelTexture.Bounds, GameOverLabelTexture)
         {
            Name = "GameOverLabel",
            HorizontalAlignment = HorizontalAlignment.Center
         };
         GameOverContainer.AddWidget(GameOverLabel);

         GameOverBackButton = new Widget(Game1.SpriteBatch, BackButtonTexture.Bounds, BackButtonTexture)
         {
            Name = "GameOverBackButton",
            HorizontalAlignment = HorizontalAlignment.Center
         };
         GameOverContainer.AddWidget(GameOverBackButton);
      }


      public void Update(GameTime gameTime)
      {
         if(GameState == GameState.GameOver)
			{
				ClearGUI();
				SetStateForAllSounds(SoundState.Stopped);

            if(GameOverContainer == null)
            {
               BuildGameOverContainer();

               // Write high score
               if(Score > HighScore)
               {
                  using(IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
                  {
                     using(var writer = new BinaryWriter(file.CreateFile("save")))
                     {
                        writer.Write(Score);
                     }
                  }
               }
            }
			}
			else if (GameState == GameState.Paused)
			{
				ClearGUI();
				BuildPausedContainer();
				SetStateForAllSounds(SoundState.Paused);
			}
			else if(GameState == GameState.HomeMenuShowing)
			{
				if(HomeContainer == null)
				{
					ClearGUI();
					BuildHomeContainer();
				}
			}
			else if(GameState == GameState.Playing)
			{
				ClearGUI();

				if (IsTrial && Score > 6000)
				{
					// Pause the game while the user is prompted.
					GameState = GameState.Paused;

					// MessageBox will have "OK" and "Cancel" buttons.
					List<String> mbList = new List<string> { "OK", "Cancel" };

					// BeginShowMessageBox is asynchronous. We define the method PromptPurchase as the callback.
					Guide.BeginShowMessageBox("Max trial score reached.", "Click OK to buy the game.", mbList, 0, MessageBoxIcon.None, PromptPurchase, null);
				}
			}

         // If screen is being touched a GameState change may occur.
         HandleTouches();

         // Updates can only occur when the game is running!
         if(GameState != GameState.Playing)
         {
            return;   
         }

         for(int i = 0; i < GameEntityList.Count; i++)
         {
            GameEntityList[i].Update(gameTime);
         }

         PhysicsEngine.Update(gameTime);
         FontParticleEngine.Update(gameTime);
         ParticleEngine.Update(gameTime);
      }


      private void HandleTouches()
      {
         var touches = TouchPanel.GetState();

         if(touches.Count > 0)
         {
				// If the game has been scaled, this will be needed to put the touches back in place so the game can read them.
				// Remember... the actual touch bounds have not changed, they just look like they have due to scaling.
				var inverseOfGlobalTransform = new Vector2(1/Game1.GlobalTransformation.X, 1/Game1.GlobalTransformation.Y);

            // Touches will change GameState or, if MenuShowing, navigate within menu system.
         	var touch = touches[0].Position * inverseOfGlobalTransform;

            // Only process on initial touch (when flag is not yet set).
            if(TouchesHaveBeenProcessed)
            {
               return;
            }

            if(GameState == GameState.Playing)
            {
               /*
                * Touching the screen anywhere while playing pauses the game. 
                */

            	const int offset = 75 ;
            	var gameBounds = Game1.GameBounds;
            	if(touch.X > gameBounds.Left+offset && touch.X < gameBounds.Right-offset &&
						touch.Y > gameBounds.Top+offset && touch.Y < gameBounds.Bottom-offset)
					{
						ClearGUI();
						GameState = GameState.Paused;
						BuildPausedContainer();
						SetStateForAllSounds(SoundState.Paused);
            	}
            }
            else if(GameState == GameState.Paused)
            {
               if(PausedBackButton.Contains(touch))
               {
                  ClearGUI();
                  GameState = GameState.Playing;
                  SetStateForAllSounds(SoundState.Playing);
               }
            }
            else if(GameState == GameState.GameOver)
            {
               if(GameOverBackButton.Contains(touch))
               {
                  ClearGUI();
                  GameState = GameState.HomeMenuShowing;
                  BuildHomeContainer();
               }
            }
            else if(GameState == GameState.HomeMenuShowing)
            {
               if(PlayButton.Contains(touch))
               {
                  ClearGUI();
                  GameState = GameState.Playing;
                  ResetGame();
               }
               else if(InfoButton.Contains(touch))
               {
                  ClearGUI();
                  GameState = GameState.InfoMenuShowing;
                  BuildInfoContainer();
               }
            }
            else if(GameState == GameState.InfoMenuShowing)
            {
               if(InfoBackButton.Contains(touch))
               {
                  ClearGUI();
                  GameState = GameState.HomeMenuShowing;
                  BuildHomeContainer();
               }
            }

            TouchesHaveBeenProcessed = true;
         }
         else
         {
            if(TouchesHaveBeenProcessed)
            {
               TouchesHaveBeenProcessed = false;
            }
         }
      }


      private void ClearGUI()
      {
         GuiContainer.Children.Clear();

         HomeContainer = null;
         PlayButton = null;
         InfoButton = null;

         InfoContainer = null;
         InfoLabel = null;
         HowToPlayLabel = null;
         InfoBackButton = null;

         PausedContainer = null;
         PausedLabel = null;
         PausedBackButton = null;

         GameOverContainer = null;
         GameOverLabel = null;
         GameOverBackButton = null;
      }


      public void Draw()
      {
         Game1.GraphicsDevice.Clear(Color.Black);

			Game1.SpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend, null, null, null, null, Game1.GlobalScaleMatrix);

         if(GameState == GameState.Playing)
         {
            // Draw the background
            Game1.SpriteBatch.Draw(BackgroundTexture,
                                   Game1.GameBounds,
                                   null,
                                   Color.White,
                                   0f,
                                   Vector2.Zero,
                                   SpriteEffects.None,
                                   BackgroundDepth);

            // Draw the entities
            foreach(GameEntity gameEntity in GameEntityList)
            {
               gameEntity.Draw();
            }

            // Draw the score
            Game1.SpriteBatch.DrawString(ScoreFont,
                                         "Score: " + Score,
                                         new Vector2(Game1.HudBounds.Left, Game1.HudBounds.Top + 10),
                                         Color.White);

            // Draw the  high score
            Game1.SpriteBatch.DrawString(ScoreFont,
                                         "High: " + HighScore,
                                         new Vector2(Game1.HudBounds.Left + 180, Game1.HudBounds.Top + 10),
                                         Color.White);

            // Draw the health
            Game1.SpriteBatch.DrawString(ScoreFont,
                                         "Life: " + Health + "%",
                                         new Vector2(Game1.HudBounds.Right - 120, Game1.HudBounds.Top + 10),
                                         Color.White);

            // Draw font particles and particles
            FontParticleEngine.Draw();
            ParticleEngine.Draw();
         }
         else
         {
            GuiContainer.Draw();

            if(GameState == GameState.GameOver)
            {
               // Draw the score
               string score = "Score: " + Score;
               Vector2 scoreSize = GameOverFont.MeasureString(score);
               Vector2 scorePosition = new Vector2(Game1.GameBounds.X + (Game1.GameBounds.Width - scoreSize.X) / 2, 
                                                   Game1.GameBounds.Y + (Game1.GameBounds.Height - scoreSize.Y) / 2);
               Game1.SpriteBatch.DrawString(GameOverFont,
                                            score,
                                            scorePosition,
                                            Color.White);

               // Draw the high score
               string highScore = "High Score: " + (HighScore > Score ? HighScore : Score);
               Vector2 highScoreSize = GameOverFont.MeasureString(highScore);
               Vector2 highScorePosition = new Vector2(Game1.GameBounds.X + (Game1.GameBounds.Width - highScoreSize.X) / 2, 
                                                       scorePosition.Y + scoreSize.Y + 25);
               Game1.SpriteBatch.DrawString(GameOverFont,
                                            highScore,
                                            highScorePosition,
                                            Color.White);

            }
         }

         Game1.SpriteBatch.End();
      }


		private void PromptPurchase(IAsyncResult ar)
		{
			// Complete the ShowMessageBox operation and get the index of the button that was clicked.
			int? result = Guide.EndShowMessageBox(ar);

			// Clicked "OK", so bring the user to the application's Marketplace page to buy the application.
			if (result.HasValue && result == 0)
			{
				Guide.ShowMarketplace(PlayerIndex.One);
			}

			GameState = GameState.GameOver;
		}

   }
}